package com.fone.player.billing.impl;

import java.util.ArrayList;
import java.util.Timer;
import java.util.TimerTask;

import android.content.Context;
import android.content.Intent;
import android.os.Handler;
import android.widget.Toast;

import com.fone.player.ApplicationManage;
import com.fone.player.R;
import com.fone.player.activity.pay.FoneThirdPayActivity;
import com.fone.player.billing.IFonePayManager;
import com.fone.player.billing.util.FoneConstants;
import com.fone.player.billing.util.common.PayEngine;
import com.fone.player.client.Callback;
import com.fone.player.client.Error;
import com.fone.player.client.Request;
import com.fone.player.client.UsRst;
import com.fone.player.sns.UserInfoManager;
import com.fone.player.util.ActivityQueue;
import com.fone.player.util.FoneUtil;
import com.fone.player.util.L;

public class FonePayManager implements IFonePayManager {

	private static final String TAG = "FonePayManager";
	private static Context mContext;
	private UsCallBack mUsCallBack;
	// private LoginCallBack mLoginCallBack;
	private Handler mHandler;
	private static int MONTH_PAY = 1;
	private static int CHARGE_PAY = 2;
	private static int VIP_PAGE = 3;
	private static final int ON_MONTH_PAY_START = 0;
	private static final int ON_MONTH_PAY__SUCCESS = 1;
	private static final int ON_CHARGE_PAY_START = 2;
	private static final int ON_CHARGE_PAY_SUCCESS = 3;
	private static final int REQUEST_USER_INFO_SUCCESS = 4;
	private static FonePayManager mFonePayManager;
	private static String mLoginFrom, mFeeFrom, mclid;
	private ArrayList<String> mUsers;
	String mLoadUrl = "";

	private FonePayManager(Context context) {
		mContext = context;
		initData();
	}

	private void initData() {
		mUsCallBack = new UsCallBack();
	}

	public static void initFonePayManagerInstance(Context context) {
		mContext = context;
		if (null == mFonePayManager) {
			mFonePayManager = new FonePayManager(mContext);
		}
	}

	public static FonePayManager getInstance() {
		if (null == mContext) {
			throw new IllegalStateException(" FonePayManager has not been initialized ");
		}
		if (null == mFonePayManager) {
			mFonePayManager = new FonePayManager(mContext);
		}
		return mFonePayManager;
	}

	@Override
	public void startThirdPay(int type, String from, String url) {

		if (type == CHARGE_PAY) {
			mLoadUrl = "充值url";
			startActivity(type, mLoadUrl);
		} else if (type == MONTH_PAY) {
			mFeeFrom = from;
			mLoadUrl = "包月url";
			startActivity(type, url);
		} else {
			L.i(TAG, "type error");
		}

	}

	/**
	 * 根据计费类型进入不同计费分支
	 * 
	 * @param type
	 *            计费类型 包月： FoneConstants.DO_VIP_ACTION 充值:
	 *            FoneConstants.DO_CHARGE_ACTION
	 * @param loginfrom
	 *            登录来源上报( FoneConstants.From... )1 点击头像注册 2 点击立即充值 3 点击成为VIP 4
	 *            付费影片计费跳转 5点击vip频道 加入vip按钮 6 点击权利页按钮跳转到登陆,7 其他
	 * @param comefrom
	 *            计费来源上报 (FoneConstants.FEE_FROM...) 1
	 *            通过快速播放点击计费影片产生订购（即：在快速播放里点了计费影片的播放或下载产生订购） 4
	 *            通过我的空间进行订购(即：在‘我的空间’里点击“加入vip”产生的订购)5 通过搜索到计费影片播放产生订购 6
	 *            通过计费栏目（如计费专题等）产生订购 7 通过播放push计费影片进行订购8 通过活动进行订购
	 * @param clid
	 *            栏目id
	 */
	@Override
	public void startPay(int type, String loginfrom, String feefrom, String clid) {
		// 根据计费类型启动不同activity
		mclid = clid;
		mFeeFrom = feefrom;
		mLoginFrom = loginfrom;
		if (!FoneUtil.isNetOkWithToast(ApplicationManage.getGlobalContext())) {
			return;
		}
		if (type == MONTH_PAY) {
			L.i(TAG, "goto_Moth_Pay", MONTH_PAY);
			if (UserInfoManager.isLogin()) {
				L.i("用户状态", "登录" + UserInfoManager.getUserSqid());
			} else {
				L.i("用户状态", "未登录");
			}
			if (FoneUtil.isNetOkWithToast(mContext)) {
				Request.getInstance().us("0", mUsCallBack);
			}
		} else if (type == CHARGE_PAY) {
			L.i(TAG, "fee_type_error", type);
			startActivity(type, null);
		}
	}

	private void startActivity(int type, String url) {
		L.i(TAG, "no_sim_card,dothirdPay:type", type);
		Intent intent;
		if (ActivityQueue.popIndex(0) != null) {
			intent = new Intent(ActivityQueue.popIndex(0), FoneThirdPayActivity.class);
		} else {
			intent = new Intent(mContext, FoneThirdPayActivity.class);
		}
		intent.putExtra("type", type);
		intent.putExtra("loginfrom", mLoginFrom);
		intent.putExtra("payfrom", mFeeFrom);
		intent.putExtra("clid", mclid);
		intent.putExtra("url", url);
		intent.putExtra("userlist", mUsers);
		if (ActivityQueue.popIndex(0) != null) {
			ActivityQueue.popIndex(0).startActivity(intent);
		} else {
			intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
			mContext.startActivity(intent);
		}
	}

	@Override
	public void testStarPay(int type, String from) {
		// TODO 单独测试微信支付 支付宝支付 先 请求us 获取是否有seqid 有的话判断登录 无的话SP计费
		// 单点测试三方支付
		// startThirdPay(type, from);

		// 单独测试SP计费

		// initFonePTL(type, null);
		// wxPayInfo

	}

	private class UsCallBack implements Callback<UsRst> {

		@Override
		public void onSuccess(UsRst t) {
			// TODO us success
			if (t.error != null) {
				Toast.makeText(mContext, R.string.retry_info_error, Toast.LENGTH_LONG).show();
				L.i(TAG, "us接口失败");
				L.i(TAG, "errorcode : " + t.error.errorcode + "errormsg" + t.error.errormsg);
				return;
			}
			L.i(TAG, "xml_content_success" + t.state);
			if (UserInfoManager.isLogin() && (0 != t.state)) {
				L.i(TAG, "VIP用户 会员url " + t.url);
				FoneUtil.showToast(mContext, "您已经是VIP用户");
				L.i(TAG, "订购用户 登录状态 到VIP会员权利页面 mLoadUrl>>" + t.url + "&cipher=" + Request.getInstance().getCipher());
			} else {
				if (null != t.users && null != t.users.useridList && t.users.useridList.size() > 0) {
					mUsers = new ArrayList<String>();
					for (int i = 0; i < t.users.useridList.size(); i++) {
						mUsers.add(t.users.useridList.get(i));
					}
				}
				// 如果是从我的视频点加入VIP按钮和活动加入VIP不弹VIP权利页面 其他都弹
				if (!(FoneConstants.FEE_FROM_BE_VIP.equals(mFeeFrom) || FoneConstants.FEE_FROM_ACTIVITY.equals(mFeeFrom))) {
					String url = t.url;
					startActivity(MONTH_PAY, url);
					return;
				}
				startActivity(MONTH_PAY, null);
			}
		}

		@Override
		public void onFailure(Error error) {
			// TODO
			L.i(TAG, "请求us接口失败 request us? failed");
			Toast.makeText(mContext, R.string.retry_network_error, Toast.LENGTH_LONG).show();
		}

	}

	@Override
	public void startSPPay(int type, String from, String url) {
		// mFeeFrom = from;
		// initFonePTL(type, url, mSPUrl);

	}

	@Override
	public String getUserState() {

		if (FoneUtil.isNetOk(ApplicationManage.getGlobalContext())) {
			String user_state_url = PayEngine.getUserVipState(ApplicationManage.getGlobalContext());
			L.i("获取用户订购状态的url", user_state_url);
			String userStatInfo = PayEngine.getUserFromFeeCenter(user_state_url, null, PayEngine.GET);
			if (userStatInfo == null) {
				return "";
			}
			L.i("获取用户订购信息：", userStatInfo);
			if (userStatInfo.contains("ed")) {
				String user_end_tiem = userStatInfo.substring(0, userStatInfo.indexOf("</ed>"));
				if ((user_end_tiem.lastIndexOf(">") + 1) < user_end_tiem.length()) {
					user_end_tiem = user_end_tiem.substring(user_end_tiem.lastIndexOf(">") + 1, user_end_tiem.length());
					UserInfoManager.saveUserFeeExpirestime(user_end_tiem, "yyyyMMdd");
				}
				// user_end_tiem = "201407100000";
				// UserInfoManager.saveUserFeeExpirestime(user_end_tiem,
				// "yyyyMMddhhmm");
			}
			if (userStatInfo.contains("os")) {
				String user_state = userStatInfo.substring(0, userStatInfo.indexOf("</os>"));
				user_state = user_state.substring(user_state.lastIndexOf(">") + 1, user_state.length());
				UserInfoManager.saveVipType(user_state);
				L.i("计费中心用户订购状态", user_state);
				return user_state;
			}
		}
		return "";

	}

	@Override
	public void getUserFeeNotif() {
		// IFonePayManager mFonePayManger = FonePayManager.getInstance();
		String user_state = getUserState();
		L.v(TAG, "getUserFeeNotif", "user_state : " + user_state);
		if ("1".equals(user_state)) {
			UserInfoManager.saveVipType(user_state);
		}
		if (FoneUtil.isNetOk(mContext)) {
			L.v(TAG, "getUserFeeNotif", "Fee ok delay 1min requestFeeNotification !!! ");
			
			Timer timer = new Timer();
			timer.schedule(new TimerTask() {
				@Override
				public void run() {
					L.v(TAG, "getUserFeeNotif", "start requestFeeNotification !!! ");
					FoneUtil.requestFeeNotification(mContext);
				}
			}, 60000);
			
		}

	}
}
